package com.day15;

/**
 * 例子:创建三个窗口卖票，总票数100张
 * <p>
 * 存在线程的安全问题，待解决。
 * <p>
 * 使用同步代码块解决继承Thread类的线程安全问题
 * <p>
 * <p>
 * 说明:在继承Thread类创建多线程时，监视器必须保持唯一即可
 */

class Windows extends Thread {

    private int ticker = 100;

    //必须保证锁的唯一
    private static Object object = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (object) {

                if (ticker > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(getName() + "还有余票,票号为:" + ticker);
                    ticker--;
                } else {
                    break;
                }
            }

        }
    }
}

class Windows2 extends Thread {

    private static int ticker = 100;



    //同步方法必须是静态的
    public void run() {
        while (true) {

            show();
        }

    }

    public static synchronized void show(){
        if (ticker > 0) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "还有余票,票号为:" + ticker);
            ticker--;
        }
    }
}


public class WindowsTest {

    public static void main(String[] args) {
        Windows windows1 = new Windows();
        Windows windows2 = new Windows();
        Windows windows3 = new Windows();


        windows1.setName("窗口1");
        windows2.setName("窗口2");
        windows3.setName("窗口3");

        windows1.start();
        windows2.start();
        windows3.start();
    }


}
